// Copyright DustedPixels.com 2008. All rights reserved.

package com.dustedpixels.jasmin.chips;

import com.dustedpixels.common.Binary;

/**
 * @author micapolos@gmail.com (Michal Pociecha-Los)
 */
public final class Z80 implements Chip {
  public short ADDRESS;
  public boolean ADDRESS_ACTIVE;
  public byte DATA;
  public boolean DATA_ACTIVE;
  public boolean RD;
  public boolean WR;
  public boolean HALT;
  public boolean M1;
  public boolean WAIT;
  public boolean MREQ;
  public boolean IORQ;
  public boolean RFSH;
  public boolean INT;
  public boolean NMI;
  public boolean RESET;
  public boolean BUSRQ;
  public boolean BUSACK;
  
  private byte A, F, B, C, D, E, H, L;
  private byte A2, F2, B2, C2, D2, E2, H2, L2;
  private byte I, R;
  private short IX, IY, SP, PC;
  private boolean IFF1, IFF2;
  private byte IM;
  
  private enum MachineCycle {
    M1,
  };
  
  private enum ClockCycle {
    T1, T2, T3, T4, T5,
  };
  
  private MachineCycle machineCycle = MachineCycle.M1;
  private ClockCycle clockCycle = ClockCycle.T1;

  private byte opcode;
  
  public void update() {
    if (machineCycle == MachineCycle.M1) {
      switch (clockCycle) {
        case T1: 
          ADDRESS = PC++;
          ADDRESS_ACTIVE = true;
          MREQ = true;
          RD = true;
          M1 = true;
          clockCycle = ClockCycle.T2;
          break;
        case T2:
          if (!WAIT) clockCycle = ClockCycle.T3;
          break;
        case T3:
          opcode = DATA;
          ADDRESS = Binary.word(I, R);
          RFSH = true;
          RD = false;
          M1 = false;
          clockCycle = ClockCycle.T4;
          break;
        case T4:
          processOpcode();
          break;
      }
    }
  }
  
  private void processOpcode() {
    // TODO(micapolos): Implement
    //System.out.println("Opcode: " + opcode);
    clockCycle = ClockCycle.T1;
  }
}
